#!/usr/bin/env python2
#-*- coding: utf-8 -*-


import os
import re
import json
import time
import sys
import cgi
import web
import uuid
import httplib2
import httplib
import traceback
import subprocess
import datetime


from Umpweb.common import log
from Umpweb.db import api as db_api
from Umpweb.common.utils import login_required
from Umpweb.common import utils
from Umpweb.base import render_jinja
from Umpweb import defs

from Ump.common.config_base import ConfigManager



LOG = log.get_log('Umpweb.webapps.import')


render = render_jinja('static/templates/import', encoding='utf-8',)


config = ConfigManager(defs.DB_CFG_PATH, section='mysql')


class Import(object):
    def __init__(self):
        self.abs_path = os.path.dirname(os.path.realpath(__file__))
        self.user = web.ctx.session.user
        self.conf_path = os.path.join('/'.join(self.abs_path.split('/')[:-4]), 'etc/ump')

    def GET(self):
        x = web.input()
        return  render.config_import()

    @login_required
    def POST(self):
        webfile = web.webapi.rawinput().get('upload')
        web.header("Content-Type", "application/json")
        random_by_uuid = str(uuid.uuid1())
        temp_dir = os.path.join(self.abs_path, random_by_uuid)
        os.makedirs(temp_dir)

        filepath = webfile.filename.replace('\\','/')       # replaces the windows-style slashes with linux ones.
        filename = filepath.split('/')[-1]                  # splits the and chooses the last part (the filename with extension)

        uploadfile = "%s/%s" % (temp_dir, filename)
        with open(uploadfile,'w') as fout:                  # creates the file where the uploaded file should be stored
            fout.write(webfile.file.read())                 # writes the uploaded file to the newly created file.

        #name contain a string need transferred 
        filename = ''.join(['\%s' % i for i in list(filename)])
        uploadfile = "%s/%s" % (temp_dir, filename)

        LOG.info('uploadfile %s, temp_dir %s' % (uploadfile, temp_dir))

        tar_cmd = 'tar  -xf %s -C %s/'%(uploadfile, temp_dir)
        print utils._exec_pipe(tar_cmd, is_raise=True)

        file_list = os.listdir(temp_dir)
        LOG.info('%s' % file_list)

        if not file_list:
            detail = u'导入文件包不能为空'
            LOG.info('%s' % detail)
        else:
            for file_ in file_list :
                _filename_intar = '%s/%s' % (temp_dir, file_)
                LOG.info('_filename_intar=%s' % _filename_intar)
                if file_ == 'ump.conf':
                    cmd = 'rm -f %s/%s; cp -f %s %s/' % (self.conf_path, file_, _filename_intar, self.conf_path)
                    LOG.info('cmd=%s' % cmd)
                    utils._exec_pipe(cmd)

                if file_.endswith("sql"):

                    cmd = 'mysql -u %s --password="%s" %s < %s' \
                        % (config.get('user'), config.get('password') , config.get('database'), _filename_intar)

                    LOG.info('sql import cmd===============%s' % cmd)
                    utils._exec_pipe(cmd)
                    LOG.info('success')

        cmd = 'rm -rf %s/' % temp_dir
        LOG.info('rm temp cmd==========%s' % cmd)
        utils._exec_pipe(cmd)

        values = {
            'user_id': web.config._session.user.id,
            'operation': u'导入配置',
            'resource': "导入",
            'oplog_obj': u"system",
            'status':u"done",
            'detail':u''
        }
        body={"EventCreate":{"params":values}}
        return utils.web_return(body)


class Export(object):
    def __init__(self):
        self.abs_path = os.path.dirname(os.path.realpath(__file__))

    def GET(self):
        temp_dir = os.path.join(self.abs_path, str(uuid.uuid1()))
        os.makedirs(temp_dir)
        ump_conf_path = os.path.join('/'.join(self.abs_path.split('/')[:-4]), 'etc/ump/ump.conf')
        utils._exec_pipe('cp %s %s' % (ump_conf_path, temp_dir))
        LOG.info('%s' % os.listdir(temp_dir))
        tar_cmd = 'tar -C %s -cf %s/exportconfig.tar mysql ump.conf' % (temp_dir, temp_dir)
        cmd = 'mysqldump -u%s --password="%s" %s > %s/exportconfig.sql' %\
                         (config.get('user'), config.get('password') , config.get('database'), temp_dir)

        utils._exec_pipe(cmd)
        tar_cmd = 'tar -C %s -cf %s/exportconfig.tar exportconfig.sql ump.conf' % (temp_dir, temp_dir)
        utils._exec_pipe(tar_cmd)
        config_file = os.path.join(temp_dir, 'exportconfig.tar')

        try:
            f = open(config_file, "rb")
            web.header('Content-Type', 'application/octet-stream')
            web.header('Content-disposition', 'attachment; filename=exportconfig.tar')
            while True:
                c = f.read()
                if c:
                    yield c
                else:
                    break
        except Exception, e:
            LOG.info('%s' % (e))
            yield 'Error'
        finally:
            if f:
                f.close()

        os.system('rm -rf %s' % temp_dir)
